"use strict";
import axios from "axios";
import app from '@/main'
import * as types from '@/store/mutation-types'

let config = {
    // baseURL: process.env.baseURL || process.env.apiUrl || ""
    timeout: 60 * 1000, // Timeout
    withCredentials: false, // Check cross-site Access-Control
};

const _axios = axios.create(config);

_axios.interceptors.request.use(
    function(config) {
        if (config.url.indexOf(types.API_URL) != -1) {
            const token = app.config.globalProperties.ls.get(types.ACCESS_TOKEN)
            if (token) {
                config.headers['Authorization'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
            }
        }

        return config;
    },
    function(error) {

        return Promise.reject(error);
    }
);

// Add a response interceptor
_axios.interceptors.response.use(
    function(response) {
        return response;
    },
    function(error) {
        // loadingHide()
        // message.loadingHide()
        console.log('异常：', error)
        if (error.response) {
            const data = error.response.data

            if (data.__abp && data.error) {
                // ABP自定义错误处理
                if ((data.error.code === 300 || data.error.code === 0)) {
                    message.error(data.error.details || data.error.message)
                } else if (data.error.code === 301) {
                    app.config.globalProperties.$message.error(data.error.details || data.error.message)
                    location.href = '/login?redirect=' + escape(location.href)
                }
                return Promise.reject(data.error)
            }
            if (error.response.status !== 200) {
                app.config.globalProperties.$message.error(data.exceptionMessage || data.message, 3)
                return Promise.reject(data)
            }
        } else if (error.message.includes('timeout')) {
            // message.error('网络超时')
            return Promise.reject(error) // reject这个错误信息
        }
        return Promise.reject(error)
    }
);

export {
    _axios as axios
}